/*
 * Copyright (c) $today.year-Now http://www.zxpnet.com All rights reserved.
 */

package com.zxp.springboot.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.db.DbUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationContextInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @desc:
 * @author: shollin
 * @date: 2021/6/19/019 22:33
 */
@Slf4j
//@AutoListener
@Component
public class MyApplicationListener implements ApplicationListener<ApplicationContextInitializedEvent>,Ordered {

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 100;
    }

    @Override
    public void onApplicationEvent(ApplicationContextInitializedEvent applicationContextInitializedEvent) {

        log.debug("MyApplicationListener " + applicationContextInitializedEvent.getTimestamp());

        // 获取environment参数
        ConfigurableEnvironment environment = applicationContextInitializedEvent.getApplicationContext().getEnvironment();

        // 初始化ApplicationPropertiesContext
        //ApplicationPropertiesContext.getInstance().initConfigs(environment);

        // 获取数据库连接配置
        String dataSourceUrl = environment.getProperty("spring.datasource.url");
        String dataSourceUsername = environment.getProperty("spring.datasource.username");
        String dataSourcePassword = environment.getProperty("spring.datasource.password");
        String driverClassName = environment.getProperty("spring.datasource.driver-class-name");

        // 如果有为空的配置，终止执行
        if (ObjectUtil.hasEmpty(dataSourceUrl, dataSourceUsername, dataSourcePassword)) {
            throw new RuntimeException("没有配数据库连接");
        }

        Connection conn = null;
        try {
            Class.forName(driverClassName);
            assert dataSourceUrl != null;
            conn = DriverManager.getConnection(dataSourceUrl, dataSourceUsername, dataSourcePassword);


        } catch (ClassNotFoundException e) {
            log.error("初始化系统配置表失败，找不到com.mysql.cj.jdbc.Driver类", e);
        } catch (SQLException sqlException) {
            log.error("初始化系统配置表失败，执行查询语句失败", sqlException);
        } finally {
            DbUtil.close(conn);
        }
    }
}
